<template>
  <el-form label-width="120px" :rules="formRules" :model="form" ref="formRef">
    <el-form-item label="部门名称" prop="name">
      <el-input v-model="form.name"></el-input>
    </el-form-item>
    <el-form-item label="部门编码" prop="code">
      <el-input v-model="form.code"></el-input>
    </el-form-item>
    <el-form-item label="部门负责人" prop="manager">
      <el-select placeholder="请选择" v-model="form.manager" value="">
        <el-option
          v-for="item in managerList"
          :key="item.id"
          :label="item.username"
          :value="item.username"
        ></el-option
      ></el-select>
    </el-form-item>
    <el-form-item label="部门介绍" prop="introduce">
      <el-input type="textarea" rows="3" v-model="form.introduce"></el-input>
    </el-form-item>
    <el-form-item>
      <el-button @click="doCancel">取消</el-button>
      <el-button type="primary" @click="doSubmit()">确定</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import {
  getManagers,
  addDepartment,
  getEditDepartment,
  editDepartment,
} from "@/api/departments";

export default {
  data() {
    const validateCode = (rules, val, callback) => {
      let codeList = this.simpleList.map((item) => item.code);
      if (this.isEdit) {
        codeList = this.simpleList
          .filter((item) => item.id !== this.curAddDeptId)
          .map((item) => item.code);
      }
      // console.log(codeList);
      codeList.includes(val)
        ? callback(new Error(`部门编号 ${val} 已被占用`))
        : callback();
    };
    const validateName = (rules, val, callback) => {
      let nameList = this.simpleList
        .filter((item) => item.pid === this.curAddDeptId)
        .map((item) => item.name);
      if (this.isEdit) {
        const index = this.simpleList.findIndex(
          (item) => item.id === this.curAddDeptId
        );
        const pid = this.simpleList[index].pid;
        nameList = this.simpleList
          .filter((item) => item.pid === pid && item.id !== this.curAddDeptId)
          .map((item) => item.name);
      }
      console.log(nameList);
      nameList.includes(val)
        ? callback(new Error(`部门名称 ${val} 已被占用`))
        : callback();
    };
    return {
      form: {
        code: "",
        introduce: "",
        manager: "",
        name: "",
      },
      managerList: [],
      formRules: {
        code: [
          { required: true, message: "部门编码输入不能为空", trigger: "blur" },
          { min: 1, max: 50, message: "长度应为1-50个字符", trigger: "blur" },
          {
            validator: validateCode,
            trigger: "blur",
          },
        ],
        introduce: [
          { required: true, message: "部门介绍输入不能为空", trigger: "blur" },
          { min: 1, max: 300, message: "长度应为1-300个字符", trigger: "blur" },
        ],
        manager: [
          {
            required: true,
            message: "部门负责人输入不能为空",
            trigger: "change",
          },
        ],
        name: [
          { required: true, message: "部门名称输入不能为空", trigger: "blur" },
          { min: 1, max: 50, message: "长度应为1-50个字符", trigger: "blur" },
          {
            validator: validateName,
            trigger: "blur",
          },
        ],
      },
    };
  },

  props: {
    curAddDeptId: {
      type: String,
      required: true,
    },
    isEdit: {
      type: Boolean,
      require: true,
    },
    simpleList: {
      type: Array,
      require: true,
    },
  },

  created() {
    this.loadManagers();
    // 编辑状态时进行数据回填
    this.showEdit(this.curAddDeptId);
  },

  methods: {
    async loadManagers() {
      const res = await getManagers();
      // console.log(res.data);
      this.managerList = res.data;
    },
    doSubmit() {
      try {
        this.$refs.formRef.validate(async (valid) => {
          if (valid) {
            if (this.isEdit) {
              await this.doEdit();
            } else {
              await this.doAdd();
            }
            this.$emit("addSuccess");
          }
        });
      } catch (err) {}
    },
    async doAdd() {
      const res = await addDepartment({
        ...this.form,
        pid: this.curAddDeptId,
      });
      console.log(res);
      this.$message.success(res.message);
    },
    async doEdit() {
      const res = await editDepartment(this.form);
      console.log(res);
      this.$message.success(res.message);
    },
    async showEdit(id) {
      if (this.isEdit) {
        const res = await getEditDepartment(id);
        console.log(res);
        this.form = { ...res.data };
      }
    },
    doCancel() {
      this.$emit("cancelAdd");
    },
  },
};
</script>
